package com.zut.blocks.base.aop;


import com.zut.blocks.base.common.CommonResponse;
import com.zut.blocks.base.exception.CommonException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ControllerAop {

    private static final Logger logger = LoggerFactory.getLogger(ControllerAop.class);

    @Around("execution(public com.zut.blocks.base.common.CommonResponse *(..))")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        CommonResponse<?> result = null;
        try {
            result = (CommonResponse<?>) pjp.proceed();
            if (pjp.getSignature().getName().endsWith("login")) {
                logger.info("{}, time: {}", pjp.getSignature(), System.currentTimeMillis() - startTime);
            } else {
                logger.info("{} args: {}, time: {}", pjp.getSignature(), pjp.getArgs(), System.currentTimeMillis() - startTime);
            }
        } catch (Throwable e) {
            result = handleException(pjp, e);
        }
        return result;
    }

    private CommonResponse<?> handleException(ProceedingJoinPoint pjp, Throwable e) {
        CommonResponse<?> result = new CommonResponse<>();
        if (e instanceof CommonException) {
            result.setMessage(e.getLocalizedMessage());
            result.setCode(CommonResponse.ERROR_CODE);
        } else {
            logger.error(pjp.getSignature() + " error ", e);

            //TODO 未知的异常，应该格外注意，可以发送邮件通知等
            result.setMessage("发生未知异常，请联系管理员。");
            result.setCode(CommonResponse.ERROR_CODE);
        }
        e.printStackTrace();
        return result;
    }
}
